<?php
class Pageley_Controller_Dispatcher_Http extends Pageley_Controller_Dispatcher_Basic {
	
    private $contextPath;
    
    public function __construct() {
        parent::__construct(new Pageley_Controller_ViewResolver_Html());
        $this->setNotFoundHandler(new Pageley_Controller_Dispatcher_Http_ErrorHandler("404", "Not Found", "error.notFound.title"));
        $this->setErrorHandler(new Pageley_Controller_Dispatcher_Http_ErrorHandler("500", "Internal Server Error", "error.server.title"));
	}
	
	public function setContextPath($contextPath) {
	    $this->contextPath = $contextPath;
	}
	
	public function dispatchRequest($parameters = null) {
        ob_start();
        session_start();
        $this->initializeRequest();
	    parent::dispatchRequest($parameters);
        ob_end_flush();
	}

	private function initializeRequest() {
		if(array_key_exists("HTTP_ACCEPT_LANGUAGE", $_SERVER)) {
			$localeString = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
			$locales = new Pageley_Util_ArrayMap();
			if($localeString) {
				$localeParts = Pageley_Util_String::split($localeString, ",");
			    foreach($localeParts as $part) {
					$loc = "";
					$part = trim($part);
					$locale = null;
					if(preg_match("/;/", $part)) {
					    $loc = Pageley_Util_String::split($part, ";");
					    $part = $loc->get(0);
					}
					$locale = $this->getLocale($part);
					if(Pageley_Log::isDebugEnabled($this)) {
						Pageley_Log::debug($this, "Adding locale '" . $part ."'.");
					}
					$locales->add($locale);
			    }
			}
			$_SESSION["pageley.locales"] = $locales;
		}
	}

	protected function getLocale($localeExpression) {
		$locale = null;
		$locParts = Pageley_Util_String::split($localeExpression, "-");
		if($locParts->size() > 1) {
			$locale = new Pageley_I18n_Locale(
				$locParts->get(0),
				strtoupper($locParts->get(1))
			);
		} else {
			$locale = new Pageley_I18n_Locale(
				$locParts->get(0)
			);
		}
		return $locale;
	}
	
    protected function processModel($model) {
        $model = parent::processModel($model);
        if($this->contextPath != null) {
            $model->put("pageley.context", Pageley_Util_String::replace($this->contextPath, "/", "."));
        }
        return $model;
    }
    
    protected function resolveView($view) {
        Pageley_Checks::parameterNotNull($view, "View");
        $view = $this->contextPath !== null ? $this->contextPath . "/" . $view : $view;
        Pageley_Log::debug($this, "Forwarding to view '" . $view . "'.");
        $this->getViewResolver()->resolveView($view);
    }
    
    protected function resolveErrorView() {
    	ob_clean();
        $this->resolveView($this->getErrorView());
    }
}